
package com.rt.schedulenew.utils.util;
import org.springframework.beans.BeansException;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.context.ApplicationContextAware;
@Component
public class SpringUtil implements ApplicationContextAware
{
    private Logger logger;
    private static ApplicationContext applicationContext;
    
    public SpringUtil() {
        this.logger = LoggerFactory.getLogger((Class)SpringUtil.class);
    }
    
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        this.logger.info("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext=" + SpringUtil.applicationContext + "========");
    }
    
    public static ApplicationContext getApplicationContext() {
        return SpringUtil.applicationContext;
    }
    
    public static Object getBean(final String name) {
        Class cla = null;
        try {
            cla = Class.forName(name);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return getApplicationContext().getBean(cla);
    }
    
    public static <T> T getBean(final Class<T> clazz) {
        return (T)getApplicationContext().getBean((Class)clazz);
    }
    
    public static <T> T getBean(final String name, final Class<T> clazz) {
        return (T)getApplicationContext().getBean(name, (Class)clazz);
    }
}
